<?php
/**
 * 积分兑换
 * @author Ice <iceinto@mallog.com.cn>
 */
class CreditAction extends BaseAction
{
    function _initialize()
    {
        $this->assign('nav', 4);
        parent::_initialize();
    }

    public function index()
    {
        $this->assign('web_title', '积分兑换');
        $limiteds = array();
        $LimitedModel = D('Limited');
        $limiteds = $LimitedModel->getNows();
        foreach ($limiteds as $key => $limited) {
            if ($limited['end_time'] < time() || $limited['surplus'] <= 0) {
                unset($limiteds[$key]);
            }
        }
        $this->assign('limiteds', $limiteds);
        $this->display();

    }

    /**
     * 优惠领取
     */
    public function detail()
    {
        $limited = $this->getDetail();
        $nowTime = time();
        //判断在是否已经开始
        if ($limited['start_time'] > $nowTime) {
            $this->success('领取还没有开始，请 ' . date('Y-m-d G:i', $limited['start_time']) . '再来！');
        }
        //判断是否已经结束
        if ($limited['end_time'] < $nowTime) {
            $this->error('领取已经结束！');
        }
        $LimitedModel = D('Limited');
        if ($limited['model'] == 2) {
            $push = $LimitedModel->getMallPush($limited['id']);
            $join = $LimitedModel->getPush($limited['id']);
            $this->assign('join', $join);
        } else {
            $push = $LimitedModel->getPush($limited['id']);
        }
        //判断是否领取完
        if ($push >= $limited['count']) {
            $this->error($limited['title'] . ' 已经全部领取完！');
        }
        if ($limited['bid']) {
            //获取品牌详细
            // TODO 融合 搜索和柜台主页显示数据 缓存
            $BrandModel = D('Brand');
            $bid = $limited['bid'];
            $brand = $BrandModel->getOneLine($limited['bid']);
            $brand['image_url'] = $BrandModel->getBrandImage($brand['image']);
            $brand['att_count'] = D('BrandAttention')->getAttCount($bid);
            //获取当前柜台活动
            $brand['dis'] = D('BrandNews')->getOneNew($limited['mid'], $limited['fid'], $bid);
            //当前用户是否关注
            $uid = getLoginUserInfo();
            if ($uid) {
                D('BrandAttention')->checkUserIsAttrBrand($uid, $brand);
            }
            $limited['brand'] = $brand;
        }
        //获取商场
        $mall = D('Market')->getById($limited['mid']);
        //获取楼层
        $floor = D('Floor')->getOne($limited['fid']);
        //获取展示图
        $slide = D('Slide')->getBrandOne($brand['id']);
        //获取最近热门积分兑换
        $credits = $this->getHotCredit();
        $this->seoSet($limited['title'], $limited['title'], msubstr(hh($limited['content']), 0, 200));
        $this->assign('push', $limited['count'] - $push);
        $this->assign('limited', $limited);
        $this->assign('mall', $mall);
        $this->assign('floor', $floor);
        $this->assign('credits', $credits);
        $this->assign('slide', $slide);
        $this->display();
    }

    /**
     * 获取访问优惠信息
     * @return Array
     * @author Ice <iceinto@mallog.com.cn>
     */
    private function getDetail()
    {
        $id = intval($this->_get('id'));
        if (!$id) {
            $this->error('获取信息数据传递错误！');
        }
        $LimitedModel = D('Limited');
        $limited = $LimitedModel->find($id);
        if ($limited) {
            $limited['image_url'] = $LimitedModel->getManagedUrl($limited['image'], 'limited');
            $limited['banner_image_url'] = $LimitedModel->getManagedUrl($limited['banner_image'], 'limited');
            return $limited;
        } else {
            $this->error('获取优惠详细获取失败！');
        }
    }

    /**
     * ajax领取前验证
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function checkReceive()
    {
        $data = '';
        $status = 0;
        $uid = getLoginUserInfo();
        $user = M('Users')->find($uid);
        $id = intval($this->_get('id'));
        if (!$id) {
            $data = '优惠标识没有传递！';
        } else if ($uid && $user) {
            $LimitedModel = D('Limited');
            $LimitedUsersModel = D('LimitedUsers');
            //判断用户认证手机情况
            if (!$user['phone'] || !$user['status'] == 2) {
                $data = '你的手机还没有绑定！请尽快绑定！';
            } else {
                $limited = M('Limited')->find($id);
                if ($limited) {
                    if ($limited['end_time'] < time()) {
                        $data = '当前领取已经结束啦！请关注网站其他领取！';
                    }
                    $lid = $limited['id']; //优惠标示
                    $receiveMaxCount = $limited['user_max'];
                    //判断是否领取完
                    $push = 0;
                    //根据不同类型获取不同发送数量
                    if ($limited['model'] == 2) {
                        $push = $LimitedModel->getMallPush($limited['id']);
                    } else {
                        $push = $LimitedModel->getPush($limited['id']);
                    }
                    if ($push >= $limited['count']) {
                        $data = $limited['title'] . ' 已经全部领取完！';
                    }
                    //判断当前用户是否已经领取过
                    $receiveCount = $LimitedUsersModel->checkUserReceiveCount($uid, $lid);
                    if ($receiveCount >= $receiveMaxCount) {
                        $data = '你已经领取过 ' . $receiveCount . ' 份啦！不能再领取啦！';
                    }
                    $dayMax = intval($limited['day_max']);
                    $phone = $user['phone'];
                    //判断今天领取数量是否超过设置最大领取数量
                    if ($dayMax != 0) {
                        $dayCount = $LimitedUsersModel->dayUsersCount($lid);
                        if ($dayCount >= $dayMax) {
                            $data = '当前领取数量已经到达当天领取最多数 ' . $dayMax . '！请明天再来！';
                        }
                    }
                    //验证积分是否够用
                    $rsNum = $this->checkUserCredit($uid, $limited['every_use_count']);
                    if (!$rsNum) {
                        $data = '用户积分不足！';
                    }
                } else {
                    $data = '获取优惠详细获取失败！';
                }
            }
        } else {
            $data = '请先登陆！';
            $status = 3;
        }
        if (empty($data)) {
            $status = 1;
        }
        $this->ajaxReturn($data, '', $status);
    }

    /**
     * 优惠领取处理
     * @author Ice <iceinto@mallog.com.cn>
     */
    public function receive()
    {
        $uid = getLoginUserInfo();
        $user = M('Users')->find($uid);
        if ($uid && $user) {
            $LimitedModel = D('Limited');
            //判断用户认证手机情况
            if (!$user['phone'] || !$user['status'] == 2) {
                $this->assign('jumpUrl', U('/member/setting', null, false, false));
                $this->error('你的手机还没有绑定！请尽快绑定！');
            }
            //判断当前用户是否已经认证
            $this->checkUsePhone($uid);
            //判断优惠标示是否正确
            $limited = $this->getDetail();
            //判断优惠信息是否已经过期
            if ($limited['end_time'] < time()) {
                $this->error('当前领取已经结束啦！请关注网站其他领取！');
            }
            $lid = $limited['id']; //优惠标示
            $receiveMaxCount = $limited['user_max'];
            //判断是否领取完
            $push = 0;
            //根据不同类型获取不同发送数量
            if ($limited['model'] == 2) {
                $push = $LimitedModel->getMallPush($limited['id']);
            } else {
                $push = $LimitedModel->getPush($limited['id']);
            }
            if ($push >= $limited['count']) {
                $this->error($limited['title'] . ' 已经全部领取完！');
            }
            //判断当前用户是否已经领取过
            $receiveCount = D('LimitedUsers')->checkUserReceiveCount($uid, $lid);
            if ($receiveCount >= $receiveMaxCount) {
                $this->assign('jumpUrl', U('/credit/' . $lid));
                $this->error('你已经领取过 ' . $receiveCount . ' 份啦！不能再领取啦！');
            }
            $dayMax = intval($limited['day_max']);
            $phone = $user['phone'];
            //判断今天领取数量是否超过设置最大领取数量
            if ($dayMax != 0) {
                $dayCount = D('LimitedUsers')->dayUsersCount($lid);
                if ($dayCount >= $dayMax) {
                    $this->error('当前领取数量已经到达当天领取最多数 ' . $dayMax . '！请明天再来！');
                }
            }
            //判断当前用户积分是否满足领取邀请。 为零代表不需要消耗
            if ($limited['every_use_count'] != 0) {
                //验证积分是否够用
                $rsNum = $this->checkUserCredit($uid, $limited['every_use_count']);
                if (!$rsNum) {
                    $this->error('用户积分不足！');
                }
            }
            //处理领取信息记录

            $verify = String::randString(6, 2, '0123456789');
            //成功添加领取操作
            $data = array();
            $data['lid'] = $lid;
            $data['uid'] = $uid;
            $data['create_time'] = time();
            $data['create_ip'] = get_client_ip();
            $data['phone'] = $user['phone']; //应用到用户信息
            $data['verify'] = $verify;
            $rs = M('LimitedUsers')->add($data);
            if ($rs) {
                //获取领取地址
                $fMall = D('Market')->getById($limited['mid']);
                $address = $fMall['name'];
                if ($limited['fid']) {
                    $fFloor = D('Floor')->getById($limited['fid']);
                    $address .= $fFloor['sain'];
                }
                //发送短信通知
                $smsBody = $limited['title'] . '领取手机认证码：' . $verify . '领取地点：' . $address . C('SMS_FOOT');
                $smsUser = array();
                $smsUser[$uid] = $phone;
                $rs = smsSend($smsUser, $smsBody); //执行发送
                if ($rs) {
                    //积分处理
                    if ($limited['every_use_count'] != 0) {
                        //修改积分
                        D('CreditUser')->change($uid, 4, $limited['every_use_count']);
                    }
                    //执行跳转
                    $this->assign('jumpUrl', U('/credit/' . $lid));
                    $this->success('你的领取成功！如果没有收到短信，可以通过用户中心-我的优惠进行短信重新发送。');
                } else {
                    $this->error('短消息发送失败，请联系客服处理！');
                }
            } else {
                $this->error('你的领取失败！请重新进行领取！');
            }

        } else {
            $this->assign('jumpUrl', U('/login'));
            $this->error('请先登陆！');
        }
        $this->assign('user', $user);
        $this->display();
    }

    /**
     * 检查积分数量
     * @param int $uid 用户
     * @param int $num 积分数
     * @param int $tid 类型
     * @author Ice <iceinto@mallog.com.cn>
     */
    private function checkUserCredit($uid, $num, $tid = 1)
    {
        $map = array();
        $map['uid'] = $uid;
        $map['tid'] = $tid;
        $credit = M('CreditUser')->where($map)->find();
        $rsNum = intval($credit['num']) - $num;
        if ($rsNum > 0) {
            return $rsNum;
        } else {
            return false;
        }
    }

    /**
     * 根据用户验证是否已经手机认证
     * @param int $uid 用户标识
     * @author Ice <iceinto@mallog.com.cn>
     */
    private function checkUsePhone($uid)
    {
        $result = D('Users')->checkUsePhone($uid);
        if (!$result['status']) {
            $this->assign('jumpUrl', U('/member/setting', null, false, false));
            $this->error('你必须自己通过手机号码认证！请尽快认证！');
        }
    }
}

?>